# frozen_string_literal: true

require 'active_support/all'
# This is a WebSocket / SSE notification example application.
#
# In this example, WebSocket sub-protocols are explored.
#
# Running this application from the command line is easy with:
#
#      iodine
#
# Or, in a single thread and a single process:
#
#      iodine -t 1 -w 1
#
# Test using:
#
#      var subprotocol = "echo"; // or "chat"
#      ws = new WebSocket("ws://localhost:3000/Mitchel", subprotocol);
#      ws.onmessage = function(e) { console.log(e.data); };
#      ws.onclose = function(e) { console.log("Closed"); };
#      ws.onopen = function(e) { e.target.send("Yo!"); };

Iodine.on_state(:pre_start) do
  IO.binwrite('pids/wsserver.pid', "#{Process.pid}\r\n")
end

# Iodine.on_state(:on_finish) do
#   File.delete('pids/wsserver.pid')
# end

# Chat clients connect with the "chat" sub-protocol.
class ChartClient
  def on_open(client)
    @nickname = client.env['PATH_INFO'].to_s.split('/')[1] || 'Guest'
    client.subscribe :chart
    # client.publish :chart, { channel: 'chart', cpu_rate: 40, ram_rate: 40 }.to_json
  end

  def on_close(client)
    client.publish :chart, '333'
  end

  def on_shutdown(client)
    client.write 'Server is shutting down... disconnecting all clients. Goodbye.'
  end

  def on_message(client, message)
    puts 'message received'
    puts message
    params = JSON.parse(message)
    puts params
    client.publish :chart, message
    # client.publish :chart, { 'namespace': 'chart', 'action': 'updateChart', channel: 'chart',
    #                          cpu_rate: params['cpu_rate'], ram_rate: params['ram_rate'] }.to_json
  end
end

# # Echo clients connect with the "echo" sub-protocol.
# class MessageClient
#   def on_open(client)
#     client.write 'You established an echo connection.'
#   end

#   def on_shutdown(client)
#     client.write 'Server is shutting down... goodbye.'
#   end

#   def on_message(client, message)
#     client.write message
#   end
# end

# Rack application module
module APP
  # the allowed protocols
  CHART_PROTOCOL_NAME = 'chart'
  MSG_PROTOCOL_NAME = 'message'
  PROTOCOLS = [CHART_PROTOCOL_NAME, MSG_PROTOCOL_NAME].freeze

  # the Rack application
  def call(env)
    return [200, {}, ['Hello World']] unless env['rack.upgrade?']

    env['rack.upgrade'] = ChartClient.new
    [101, {}, []]
  end

  # make functions availble as singleton module
  module_function :call
end

run APP
